"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.others = exports.github = exports.gitee = void 0;
const tslib_1 = require("tslib");
const crypto = tslib_1.__importStar(require("crypto"));
const http_1 = require("./http");
function gitee(req, secret = '') {
    const query = http_1.getHttpQuery(req);
    const gtoken = req.headers['x-gitee-token'];
    // 签名秘钥
    if (query.sign && query.timestamp) {
        if (Math.abs(Date.now() - query.timestamp) < 3600000) {
            const token = crypto.createHmac('sha256', secret).update(`${query.timestamp}\n${secret}`).digest('base64');
            return token === gtoken;
        }
    }
    // webhook 密码
    else {
        return secret === gtoken;
    }
    return false;
}
exports.gitee = gitee;
function github(req, secret = '', rawBody) {
    const token = 'sha1=' + crypto.createHmac('sha1', secret).update(rawBody).digest('hex');
    return token === req.headers['x-hub-signature'];
}
exports.github = github;
// gitlab, gogs, gitea
function others(req, secret = '', rawBody) {
    let xtoken = '';
    for (const key in req.headers) {
        if (/^x-[\da-z-]+-(token)|(signature)$/i.test(key)) {
            const v = req.headers[key];
            xtoken = typeof v === 'string' ? v : '';
            break;
        }
    }
    if (xtoken === secret) {
        return true;
    }
    const token = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
    return token === xtoken;
}
exports.others = others;
function default_1(req, secret = '', rawBody) {
    if (req.headers['x-gitee-token']) {
        return gitee(req, secret);
    }
    else if (req.headers['x-hub-signature']) {
        return github(req, secret, rawBody);
    }
    else {
        return others(req, secret, rawBody);
    }
}
exports.default = default_1;
